<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="50%"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      :label-width="$i18n.locale === 'en-US' ? '170px' : '140px'"
    >
      <el-row :gutter="30">
        <el-col :span="24">
          <el-form-item label="套票名称" prop="jointName">
            <el-input v-model="dataForm.jointName"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="出发港口" prop="startPortName">
            <el-select
              style="width: 100%"
              v-model="dataForm.startPortName"
              placeholder="出发港口"
              clearable
            >
              <el-option
                v-for="(item, index) in startOptions"
                :key="index"
                :value="item"
                :label="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="到达港口" prop="endPortName">
            <el-select
              style="width: 100%"
              v-model="dataForm.endPortName"
              placeholder="到达港口"
              clearable
            >
              <el-option
                v-for="(item, index) in endOptions"
                :key="index"
                :value="item.endPortName"
                :label="item.endPortName"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24">
          <el-form-item label="联票类型" prop="type">
            <el-radio-group v-model="dataForm.type">
              <el-radio :label="5">船+宿</el-radio>
              <el-radio :label="7">船+景</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="价格（起）" prop="startPrice">
            <el-input
              v-model="dataForm.startPrice"
              type="number"
              min="0"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所属区域名称" prop="scenicId">
            <el-select
              v-model="dataForm.scenicId"
              placeholder="所属区域"
              clearable
            >
              <el-option
                v-for="item in scenicNameList"
                :key="item.id"
                :label="item.scenicName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="景区名称" prop="boundIdsArr">
            <el-select
              v-model="dataForm.boundIdsArr"
              placeholder="景区名称"
              multiple
              clearable
            >
              <el-option
                v-for="item in scenicSpotNameList"
                :key="item.spid"
                :label="item.scenicName"
                :value="item.spid"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="套餐封面图" prop="coverImage">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="(res, file, fileList) => successHandle1(res)"
              :before-upload="(file) => beforeUploadHandle(file, 'coverImage')"
            >
              <!-- <img
                v-if="dataForm.coverImage"
                :src="dataForm.coverImage"
                class="avatar"
              /> -->
               <el-image
               class="avatar"
                v-if="dataForm.coverImage"
                :src="dataForm.coverImage"
                fit="cover"
              ></el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="套餐详情图" prop="tpDetails">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="
                (res, file, fileList) => successHandle1(res, 'tpDetails')
              "
              :before-upload="
                (file) => beforeUploadHandle(file, 'tpDetails', true)
              "
            >
              <!-- <img
                v-if="dataForm.tpDetails"
                :src="dataForm.tpDetails"
                class="avatar"
              /> -->
              <el-image
               class="avatar"
                v-if="dataForm.tpDetails"
                :src="dataForm.tpDetails"
                fit="cover"
              ></el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="规则说明" prop="reserveNotice">
            <editor-vue
              :content="dataForm.reserveNotice"
              @EditorChange="getEditor"
              ref="infoIntroduceRef"
              style="margin-top: -30px"
            ></editor-vue>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
    <!-- 裁剪框 -->
    <cropper-dlg
      v-if="showCropper"
      :dialogVisible.sync="showCropper"
      :img-file="currentFile"
      ref="vueCropper"
      @upload="cropperUpload"
    ></cropper-dlg>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
import editorVue from "@/components/editor";
export default {
  data() {
    return {
      currentFile: "",
      cropperIndex: null,
      showCropper: false, //裁剪弹框
      isCropper: true, //上传之前是否显示裁剪
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      fileList2: [],
      visible: false,
      scenicNameList: [],
      scenicSpotNameList: [],
      dataForm: {
        id: "",
        startPrice: 0,
        endPortName: "",
        endPortNo: 0,
        jointName: "",
        startPortName: "",
        startPortNo: 0,
        type: 7,
        scenicId: "",
        boundIds: "", //景区id
        boundIdsArr: [],
        tpDetails: "",
        coverImage: "",
        reserveNotice: "",
      },
      first: true,
      first1: true,
      startOptions: [],
      endOptions: [],
      placeInfo: null,
    };
  },
  components: {
    editorVue,
  },
  computed: {
    dataRule() {
      return {
        jointName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        scenicId: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        startPrice: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        reserveNotice: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        boundIdsArr: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        coverImage: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        tpDetails: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        startPortName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        endPortName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  watch: {
    "dataForm.startPortName"(newval, oldval) {
      if (this.first1) {
        this.first1 = false;
      } else {
        this.dataForm.endPortName = "";
      }
      if (this.placeInfo) {
        let ind = this.startOptions.findIndex((item) => item == newval);
        this.endOptions = this.placeInfo[newval];
      }
    },
    "dataForm.scenicId"(newval, oldval) {
      if (newval != oldval) {
        if (this.first) {
          this.first = false;
        } else {
          this.dataForm.boundIdsArr = [];
        }
        if (newval) {
          this.getScenicSpotNameList(newval);
        }
      }
    },
  },
  methods: {
    // 上传之前
    beforeUploadHandle(file, name, notCropper) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
      if (notCropper) {
        this.isCropper = false;
      } else {
        this.isCropper = true;
      }
      if (this.isCropper) {
        //显示裁剪
        this.currentFile = file;
        this.cropperIndex = name;
        this.showCropper = true;
        this.$nextTick(() => {
          this.$refs.vueCropper.init();
        });
        return false;
      }
    },

    cropperUpload(data) {
      this.showCropper = false;
      if (data != "close") {
        //裁剪成功后获取的图片
        this.$http.post("/oss/file/aliyunUpload", data).then((res) => {
          if (res.data.code == 0) {
            this.successHandle1(res.data, this.cropperIndex);
          }
        });
      }
    },
    // 上传成功
    successHandle1(res, name) {
      console.log(res);
      console.log(name);
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.dataForm[name] = res.data.url;
    },
    getEditor(val) {
      this.dataForm.reserveNotice = val;
    },
    getScenicName() {
      this.$http.get("/scenic/isscenic/selectScenicList").then((res) => {
        this.scenicNameList = res.data.data;
      });
    },
    getScenicSpotNameList(id) {
      this.$http
        .get("/scenic/isscenicspot/selectScenicList/" + id)
        .then((res) => {
          this.scenicSpotNameList = res.data.data.filter(
            //只提供收费的
            (item) => item.isBuy == 1 && item.startPrice > 0
          );
        });
    },
    queryOption() {
      this.$http
        .get("/travel/isshipportline/api/shipHotelList")
        .then(({ data: res }) => {
          this.placeInfo = res.data;
          for (let p in this.placeInfo) {
            this.startOptions = [...this.startOptions, p];
          }
          if (!this.dataForm.startPortName) {
            this.endOptions = this.placeInfo[this.startOptions[0]];
          } else {
            if (this.dataForm.startPortName) {
              let index = this.startOptions.findIndex(
                (item) => item == this.dataForm.startPortName
              );
              this.endOptions = this.placeInfo[this.startOptions[index]];
            }
          }
        });
    },
    init() {
      this.visible = true;
      this.getScenicName();
      this.dataForm.saleNum = 0;
      this.$nextTick(() => {
        setTimeout(() => {
          this.$refs.infoIntroduceRef.init();
        }, 500);
        // 船景
        this.dataForm.boundIdsArr = [];
        this.fileList2 = [];
        this.dataForm.reserveNotice = "";
        this.dataForm.tpDetails = "";
        this.startOptions = [];
        this.endOptions = [];
        this.$refs["dataForm"].resetFields();

        if (this.dataForm.id) {
          this.getInfo();
        } else {
          this.queryOption();
        }
      });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get("/scenic/joint/ticket/" + this.dataForm.id)
        .then(({ data: res }) => {
          this.first = true;
          this.first1 = true;
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          let imgArr = this.dataForm.tpDetails.split(",");
          imgArr.filter((item) => {
            this.fileList2.push({
              url: item,
            });
          });
          setTimeout(() => {
            this.$refs.infoIntroduceRef.init();
          }, 500);
          this.dataForm.boundIdsArr = this.dataForm.boundIds.split(",");
          this.queryOption();
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          if (this.dataForm.startPortName) {
            // let startPort = this.endOptions.filter(
            //   (item) => item.startPortName == this.dataForm.startPortName
            // );
            let endPort = this.endOptions.filter(
              (item) => item.endPortName == this.dataForm.endPortName
            );
            if (endPort) {
              this.dataForm.endPortNo = endPort[0].endPortNum;
              this.dataForm.startPortNo = endPort[0].startPortNum;
            }
          }

          this.dataForm.boundIds = this.dataForm.boundIdsArr.join(",");
          // let tpDetailsArr = [];
          // this.fileList2.filter((item) => {
          //   tpDetailsArr.push(item.url);
          // });
          //this.dataForm.tpDetails = tpDetailsArr.join(",");
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/scenic/joint/ticket",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>

<style lang="scss" scoped>
h3 {
  padding: 30px 0 15px;
  width: 94%;
  margin: 0 auto 30px;
  border-bottom: 1px solid #ddd;
  color: #303133;
  font-size: 22px;
  overflow: hidden;
}

.rooms .item {
  display: inline-block;
  margin-right: 15px;
  position: relative;

  .el-icon-error {
    position: absolute;
    right: 6px;
    top: -6px;
    font-size: 20px;
    color: #dd0606;
  }
}
</style>
